package com.digitalchina.lxnsy.activity.mainConsult;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.EditText;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.ConsultRefundApplyVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ApplyRefundActivity extends BaseActivity {
    @Bind(R.id.et_reason)
    EditText etReason;
    @Bind(R.id.sdv_img0)
    SimpleDraweeView sdvImg0;
    @Bind(R.id.sdv_img1)
    SimpleDraweeView sdvImg1;
    @Bind(R.id.sdv_img2)
    SimpleDraweeView sdvImg2;
    @Bind(R.id.sdv_img3)
    SimpleDraweeView sdvImg3;

    // 图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    private String consultSessionId = "";
    private SimpleDraweeView[] sdvArray = new SimpleDraweeView[4];
    private String imgs = ""; // 图片 多张以逗号隔开
    private String[] imgArray = {"", "", "", ""};
    private int select = 0;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_consult_apple_refund);
        setTitle("申请退款");
    }

    @Override
    public void initMember() {

        consultSessionId = (String) getIntent().getSerializableExtra("consultSessionId");

        //打开选择,本次允许选择的数量
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);  //显示拍照按钮
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）

        sdvArray[0] = sdvImg0;
        sdvArray[1] = sdvImg1;
        sdvArray[2] = sdvImg2;
        sdvArray[3] = sdvImg3;
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what){
                    case MSG.MSG_FILE_UPLOAD_SUCCESS: // 上传图片
                        dismissDialog();
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "fileStorage", FileVO.class);
                        if (fileVO != null) {
                            imgArray[select] = fileVO.getName();
                            setImageView(fileVO.getName());
                        }
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG_S_0:
                        ConsultRefundApplyVO vo = FastJsonUtil.getBean(msg.obj.toString(), "consultRefundApply", ConsultRefundApplyVO.class);
                        final String consultRefundApplyId = vo.getId();
                        //发送成功
                        new MaterialDialog.Builder(activity)
                                .title("提示")
                                .content("申请成功，等待客服审核。")
                                .positiveText("确定")
                                .cancelable(false)
                                .canceledOnTouchOutside(false)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        Intent i = new Intent();
                                        i.putExtra("consultRefundApplyId",consultRefundApplyId);
                                        setResult(RESULT_OK,i);
                                        finish();
                                    }
                                })
                                .show();
                        break;
                    case MSG_F_0:
                        //发送消息失败
                        showToast(msg.obj.toString() + "");
                        break;
                }
                return false;
            }
        });
    }

    private void setImageView(String fileName) {
        FrescoUtil.showImageSmall(fileName, sdvArray[select]);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    showDialog("正在上传图片...");
                    BusinessFile.imageCompressAndUpload(this, images.get(0).path, mHandler);
                }
            }
        }
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.sdv_img0, R.id.sdv_img1, R.id.sdv_img2, R.id.sdv_img3, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sdv_img0:
                selectImage(0);
                break;
            case R.id.sdv_img1:
                selectImage(1);
                break;
            case R.id.sdv_img2:
                selectImage(2);
                break;
            case R.id.sdv_img3:
                selectImage(3);
                break;
            case R.id.btn_submit:
                if(StringUtil.isEditEmpty(etReason)){
                    showToast("请输入退款原因");
                }else{
                    apply();
                }
                break;
        }
    }

    // 选择图片
    private void selectImage(int i) {
        select = i;
        if (StringUtil.isStrEmpty(imgArray[select])) {
            Intent intent = new Intent(activity, ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT);
        } else {
            new MaterialDialog.Builder(activity)
                    .title("提示")
                    .content("是否删除这张照片？")
                    .positiveText("删除")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            imgArray[select] = "";
                            Uri uri = Uri.parse("res://com.digitalchina.bigdata/" + R.drawable.selector_image_add);
                            sdvArray[select].setImageURI(uri);
                        }
                    })
                    .show();
        }

    }

    /**
     * 提交申请
     *
     */
    private void apply() {

        imgs = "";
        for (String s : imgArray) {
            if (!StringUtil.isStrEmpty(s))
                imgs += s + ",";
        }


        HttpParams params = new HttpParams();
        params.put("consultSessionId", consultSessionId);
        params.put("refundReason", etReason.getText().toString());
        params.put("imgs", imgs);

        OkHttpUtil.post(activity, URL.URL_CONSULT_APPLY_REFUND, "正在提交...", params, mHandler,
                MSG_S_0, MSG_F_0);

    }
}
